package com.heima.wemedia.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.feign.TaskFeign;
import com.heima.utils.common.JsonUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务，每秒从延迟队列中（Redis）消费任务
 */
@Component
@Slf4j
public class WmNewsTaskJob {
    @Autowired
    private TaskFeign taskFeign;

    @Autowired(required = false)
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    // @Scheduled(fixedRate = 1000)//1秒1次
    public void publishWmNewsTask(){
        //扫描Redis到期的任务
        ResponseResult<List<Task>> responseResult =
                taskFeign.pollTask(ScheduleConstants.TASK_TOPIC_NEWS_PUBLISH);
        if (responseResult.getCode().equals(200)) {
            List<Task> taskList = responseResult.getData();
            if (CollectionUtils.isNotEmpty(taskList)) {
                for (Task task : taskList) {
                    String parameters = task.getParameters();
                    WmNews wmNews = JsonUtils.toBean(parameters, WmNews.class);

                    wmNews = wmNewsMapper.selectById(wmNews.getId());
                    wmNewsAutoScanService.publishArticle(wmNews);

                    log.info("文章定时发布成功。文章ID：{}"+wmNews.getId());
                }
            }
        }

    }
}
